﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Luna.NHibernate;
using XWord.Fundamental.Data.Repositories;
using XWord.Fundamental.Domain;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;

namespace XWord.Fundamental.Data.Impl
{
    public class EtymaRepository : Repository<Etyma>, IEtymaRepository
    {
        public EtymaRepository()  
        {
        }

        public IList<Etyma> GetEtymaList()
        {
            return Session.CreateCriteria<Etyma>().
                AddOrder(Order.Asc("Name")).List<Etyma>();
        }

        public IList<T> GetEtymaList<T>()
        {
            return Session.CreateCriteria(typeof(T)).
                AddOrder(Order.Asc("Name")).List<T>();
        }


        public IList<Etymon> GetHierarchicalTree()
        {
            return Session.CreateCriteria<Etymon>()
                .Add(Restrictions.IsNull("Parent"))
                .SetFetchMode("Children", FetchMode.Eager)
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .List<Etymon>();
           
        }

        private IList<T> GetEtymaListByType<T>(Type type)
        {
            return Session.CreateCriteria<Etyma>()
             .Add(Restrictions.Eq("EtymaType", type.ToString()))
             .List<T>();
        }

        public IList<Suffix> GetSuffixList()
        {
            return GetEtymaListByType<Suffix>(typeof(Suffix));
        }

        public void SaveEtyma(Etyma etyma)
        {
            Session.SaveOrUpdate(etyma);
            Session.Flush();
        }
    }
}
